from utils.Logger import Logger
from core.FileManager import FileManager
from core.FormatManager import FormatManager
from typing import Optional

class PreviewService:
    def __init__(self):
        self.logger = Logger(__name__)
        self.file_manager = FileManager()
        self.format_manager = FormatManager()
        self.logger.info("PreviewService initialized")

    def preview_file(self, file_path: str) -> Optional[str]:
        """预览文件内容"""
        try:
            content = self.file_manager.read_file(file_path)
            if content is None:
                return None
                
            # 根据文件类型进行格式化
            if file_path.endswith('.json'):
                formatted = self.format_manager.format_json(content)
            elif file_path.endswith('.py'):
                formatted = self.format_manager.format_code(content, 'python')
            else:
                formatted = self.format_manager.format_text(content)
            
            self.logger.info(f"Preview generated for file: {file_path}")
            return formatted
        except Exception as e:
            self.logger.error(f"Failed to preview file {file_path}: {str(e)}")
            return None

    def preview_markdown(self, markdown: str) -> str:
        """预览Markdown内容"""
        try:
            import markdown2
            # 使用markdown2进行渲染，启用额外特性
            html = markdown2.markdown(
                markdown,
                extras=[
                    "fenced-code-blocks",  # 代码块
                    "tables",  # 表格
                    "footnotes",  # 脚注
                    "cuddled-lists",  # 紧凑列表
                    "task_list",  # 任务列表
                    "header-ids",  # 标题ID
                    "toc"  # 目录
                ]
            )
            # 只返回渲染后的HTML内容
            formatted = html
            self.logger.info("Markdown preview generated")
            return formatted
        except Exception as e:
            self.logger.error(f"Failed to preview markdown: {str(e)}")
            return markdown

    def preview_code(self, code: str, language: str) -> str:
        """预览代码"""
        try:
            formatted = self.format_manager.format_code(code, language)
            self.logger.info(f"Code preview generated for language: {language}")
            return formatted if formatted is not None else code
        except Exception as e:
            self.logger.error(f"Failed to preview {language} code: {str(e)}")
            return code
